<?php
declare (strict_types=1);

namespace app\common\tool;

use think\Exception;
use think\facade\Log;

class Face
{
    /**
     * 面部识别
     */
    public function identify($user, $face_image)
    {
        try {
            if(empty($user['face_image'])){
                return ['code'=> -1, 'msg'=>'用户暂未上传人脸照'];
            }
            if(empty($face_image)){
                return ['code'=> -1, 'msg'=>'请上传人脸照'];
            }

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => "https://api-cn.faceplusplus.com/facepp/v3/compare",     //输入URL
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => array('image_url1'=>$face_image,'image_url2'=>$user['face_image'], 'api_key'=>"h9kdeXzlN0dJrOPyeYHIfjq7Am0bUjtG",'api_secret'=>"ap4WBAASVxFYBLhq9jI3BtU8XpQfFcZY"),   //输入api_key和api_secret
                CURLOPT_HTTPHEADER => array("cache-control: no-cache",),
            ));
            $response = curl_exec($curl);
            $err = curl_error($curl);
            curl_close($curl);
            if ($err) {
                return ['code'=> -1, 'msg'=>$err];
            }
            Log::write("===checkFace===".$response);
            $result = json_decode($response,true);
            if(isset($result['error_message'])){
                return ['code'=> -1, 'msg'=>'人脸识别有误，请联系管理员>>'.$result['error_message']];
            }

            if(! isset($result['confidence'])){
                return ['code'=> -1, 'msg'=>'图片未返回置信值>>'.$result['error_message']];
            }
            if(! isset($result['thresholds']['1e-3']) || ! isset($result['thresholds']['1e-5']) ){
                return ['code'=> -1, 'msg'=>'未返回阈值'];
            }
            if($result['thresholds']['1e-3'] > $result['confidence'] ){
                return ['code'=> -1, 'msg'=>'人脸识别未通过'];
            }
            if($result['thresholds']['1e-5'] < $result['confidence'] ){
                return ['code'=> 1, 'msg'=>'人脸验证通过'];
            }


        }catch (Exception $e) {
            return ['code'=> -1, 'msg'=>$e->getMessage()];
        }
    }


}